package com.cqeec.bootdemo.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqeec.bootdemo.common.BaseContext;
import com.cqeec.bootdemo.common.R;
import com.cqeec.bootdemo.entity.ShoppingCart;
import com.cqeec.bootdemo.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        //往购物车插入数据
        log.info("购物车数据：{}", shoppingCart);
        //购物车里有的数据数量+1
        //怎么知道购物车里是否有该菜品
        //1.查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        if (shoppingCart.getDishId() != null) {
            queryWrapper.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        } else {
            queryWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart cart = shoppingCartService.getOne(queryWrapper);

        //判断当前用户下没有该菜品或套餐
        if (cart != null) {
            cart.setNumber(cart.getNumber() + 1);
            shoppingCartService.updateById(cart);
            return R.success(cart);
        } else {
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            return R.success(shoppingCart);
        }
    }

    //获取购物车数据
    @GetMapping("list")
    public R<List<ShoppingCart>> list() {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        queryWrapper.orderByAsc(ShoppingCart::getCreateTime);
        return R.success(shoppingCartService.list(queryWrapper));
    }

    @PostMapping("/sub")
    public R<ShoppingCart> subtract(@RequestBody ShoppingCart shoppingCart) {
        log.info("减少购物车商品数量：{}", shoppingCart);

        // 1. 查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());

        if (shoppingCart.getDishId() != null) {
            queryWrapper.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        } else {
            queryWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }

        ShoppingCart cart = shoppingCartService.getOne(queryWrapper);

        if (cart == null) {
            return R.error("购物车中未找到该商品");
        }

        // 2. 减少数量（如果数量>1则减1，否则删除该记录）
        if (cart.getNumber() > 1) {
            cart.setNumber(cart.getNumber() - 1);
            shoppingCartService.updateById(cart);
            return R.success(cart);
        } else {
            shoppingCartService.removeById(cart.getId());
            cart.setNumber(0); // 前端可能需要知道已经减到0（删除）了
            return R.success(cart);
        }
    }
    //清空购物车
    /**
     * 清空当前用户的购物车
     */
    @DeleteMapping("/clean")
    public R<String> clean() {
        // 获取当前用户ID
        Long currentUserId = BaseContext.getCurrentId();

        try {
            // 构建删除条件包装器
            LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ShoppingCart::getUserId, currentUserId);

            // 执行删除操作
            boolean removed = shoppingCartService.remove(queryWrapper);

            if (removed) {
                log.info("成功清空用户ID: {} 的购物车", currentUserId);
                return R.success("购物车已清空");
            } else {
                log.warn("用户ID: {} 的购物车本来就是空的", currentUserId);
                return R.success("购物车已经是空的");
            }
        } catch (Exception e) {
            log.error("清空购物车失败，用户ID: {}", currentUserId, e);
            return R.error("清空购物车失败");
        }
    }
}
